import { defineComponent, TransitionGroup, ref, onMounted, createVNode, render as vueRender } from "vue";
import LNotice from "./LNotice";
import { v4 } from "uuid"; 

const LNotification = defineComponent({
  name: "LNotification",
  setup: (props, { expose }) => {
    const notices = ref([]);
    function add(params) {
      params.key = v4();
      params.onClose = () => {
        remove(params.key);
      };
      notices.value.push(params);
    }
    function remove(removeKey) {
      notices.value = notices.value.filter(item => {
        return item.key !== removeKey;
      });
    }
    expose({
      add,
    });
    return () => {
      const noticeNodes = notices.value.map((node, index) => {
        return (<LNotice key={node.key} content={node.content} type={node.type} noticeKey={node.key} onClose={node.onClose} index={index} />);
      });
      return (
        <TransitionGroup name="message" mode="out-in">
          {noticeNodes}
        </TransitionGroup>
      );
    };
  },
});

LNotification.newInstance = function newNotificationInstance(properties, callback) {
  const { appContext, getContainer } = properties;
  const div = document.createElement("div");
  if (getContainer) {
    const root = getContainer();
    root.appendChild(div);
  } else {
    document.body.appendChild(div);
  }
  const LWrapper = defineComponent({
    name: "LWrapper",
    setup(props, { attrs }) {
      const notiRef = ref();
      onMounted(() => {
        callback({
          notice(noticeProps) {
            notiRef.value.add(noticeProps);
          },
          destory() {
            vueRender(null, div);
            if (div.parentNode) {
              div.parentNode.removeChild(div);
            }
          },
        });
      });
      return () => {
        return (<LNotification ref={notiRef} {...attrs}></LNotification>);
      };
    },
  });
  const vm = createVNode(LWrapper);
  vm.appContext = appContext || vm.appContext;
  vueRender(vm, div);
};

export default LNotification;